import objectUtils from "@/utils/object/index.js";
import stringUtils from "@/utils/string/index.js";
import logUtils from "@/utils/log/index.js";
import urlUtils from "@/utils/url/index.js";
import config from '@/config/index.js';

const uniUtils = objectUtils.freeze({
  toast: (msg) => {
    if (stringUtils.isString(msg)) {
      uni.showToast({
        title: msg,
        icon: 'none',
        duration: 3000
      });
    }
  },
  route: {
    go: (url, params) => {
      if (stringUtils.isString(url)) {
        let path = url;
        if (params && Object.prototype.toString.call(params) === '[object Object]') {
          path = urlUtils.params.append(path, params);
        }
        if (!config.hospitalId) {
          path = urlUtils.params.replace(path, {
            hospitalId: uni.getStorageSync("hospitalId") || ""
          })
        }
        uni.navigateTo({
          url: path,
          success: (res) => {
            if (res.errMsg === "navigateTo:ok") {
              logUtils.success("成功进入：" + url);
            } else {
              logUtils.error("进入失败：" + url);
            }
          },
          fail: (err) => {
            console.log(err)
            logUtils.error("进入失败：" + url);
          }
        });
      } else {
        logUtils.error("导航参数异常：" + url);
      }
    },
    switchTab: (url) => {
      if (stringUtils.isString(url)) {
        uni.switchTab({
          url: url,
          success: (res) => {
            if (res.errMsg === "switchTab:ok") {
              logUtils.success("成功进入：" + url);
            } else {
              logUtils.error("进入失败：" + url);
            }
          },
          fail: (err) => {
            console.log(err)
            logUtils.error("进入失败：" + url);
          }
        });
      } else {
        logUtils.error("导航参数异常：" + url);
      }
    },
    redirect: (url) => {
      if (stringUtils.isString(url)) {
        uni.redirectTo({
          url: urlUtils.params.replace(url, {
            hospitalId: uni.getStorageSync("hospitalId") || ""
          }),
          success: (res) => {
            if (res.errMsg === "redirectTo:ok") {
              logUtils.success("跳转进入成功：" + url);
            } else {
              logUtils.error("跳转进入失败：" + url);
            }
          },
          fail: (err) => {
            logUtils.error("跳转进入失败：" + url);
          }
        });
      } else {
        logUtils.error("跳转导航参数异常：" + url);
      }
    },
    back: (delta = 1) => {
      let currentRoutes = getCurrentPages();
      let page = currentRoutes[Math.max(currentRoutes.length - 1 - delta, 0)];
      uni.navigateBack({
        delta: delta,
        success: () => {
          page?.onLoad?.bind(page)(page.options);
        }
      })
    }
  },
  login: () => {
    return new Promise(async (resolve, reject) => {
      uni.login({
        provider: "weixin",
        success: (res) => {
          if (res.errMsg === "login:ok") {
            resolve(res.code);
          } else {
            logUtils.error(res.errMsg);
            reject(false);
          }
        },
        fail: (error) => {
          logUtils.error(error.toString());
          reject(false);
        }
      });
    })
  },
  pay: (config) => {
    return new Promise(async (resolve, reject) => {
      uni.requestPayment({
        provider: "wxpay",
        orderInfo: {
          appid: config.appId,
          nonceStr: config.nonceStr,
          timeStamp: config.timeStamp,
          package: config.packageValue,
          signType: config.signType,
          paySign: config.paySign
        },
        timeStamp: config.timeStamp,
        nonceStr: config.nonceStr,
        package: config.packageValue,
        signType: config.signType,
        paySign: config.paySign,
        success: (e) => {
          console.log(e)
          if (e && e.errMsg === "requestPayment:ok") {
            resolve();
          } else {
            uniUtils.toast("支付失败");
          }
        },
        fail: (e) => {
          console.log(e)
          if (e && e.errMsg.startsWith("requestPayment:fail")) {
            uniUtils.toast("您已取消支付");
          } else {
            uniUtils.toast(e.errMsg);
          }
          reject()
        }
      });
    })
  },
  requestSubscribeMessage: (type) => {
    function findTemplateIds() {
      try {
        let templateIds = uni.getStorageSync("system-subscription-templates");
        for (let i = 0; i < templateIds.length; i++) {
          if (templateIds[i].type === type) {
            return templateIds[i].templateIdList;
          }
        }
        return [];
      } catch (e) {
        return [];
      }
    }
    return new Promise(async (resolve) => {
      let templateIdList = findTemplateIds();
      if (templateIdList.length > 0) {
        uni.requestSubscribeMessage({
          tmplIds: templateIdList,
          success: (res) => {
            resolve();
          },
          fail: (err) => {
            resolve();
          }
        })
      } else {
        resolve();
      }
    })
  },
  request: {
    post: (url, params) => {
      return new Promise(async (resolve, reject) => {
        uni.request({
          url: config.baseURL + url,
          method: 'post',
          data: params,
          header: {
            "tenant-id": uni.getStorageSync("tenantId")
            // "hospital-id": uni.getStorageSync("hospitalId")
          },
          success: (response) => {
            if (response.statusCode === 200) {
              if (response.data.code === 0) {
                resolve(response.data.data);
              } else {
                uniUtils.toast(response.data.msg);
                reject(false);
              }
            } else {
              uniUtils.toast("服务异常");
              reject(response.statusCode);
            }
          },
          fail: (err) => {
            logUtils.error(err);
            reject(err);
          }
        })
      })
    }
  },
  setTabBarBadge: (num) => {
    const pages = getCurrentPages() // 获取栈实例
    const currentRoute = pages[pages.length - 1].route;
    const whiteList = [
      'pages/home/index',
      'pages/message/index',
      'pages/news/index',
      'pages/my/index'
    ]
    if (whiteList.indexOf(currentRoute) !== -1) {
      if (num === 0) {
        uni.removeTabBarBadge({
          index: 1
        })
      } else {
        uni.setTabBarBadge({
          index: 1,
          text: num > 99 ? '99+' : num.toString()
        })
      }
    }
  }
});

export default uniUtils;